from PyQt5.QtCore import QRect
from PyQt5.QtWidgets import *
import sys
import pandas as pd
import xlrd
import os
import shutil


class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setWindowTitle("文件迁移辅助工具")
        # content_layout = QHBoxLayout()
        try:
            self.initWindow()
        except Exception as e:
            self.processResult(f"读取文件错误{e}")

    def crateFileDir(self, folder_path):
        # 检查文件夹是否存在，如果不存在则创建
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

    def readXls(self, file_name, header):
        headerNum = 0
        workbook = xlrd.open_workbook(file_name, ignore_workbook_corruption=True)
        df = pd.read_excel(workbook, header=headerNum)
        return df

    def readXlsx(self, file_name, header):
        headerNum = 0
        df = pd.read_excel(file_name, header=headerNum)
        return df

    def readExcel(self, file_name, header=0, nfileNames="", nfileSegment="", nFilePathDir="", oldFilePathDir="",
                  moveFileName=""):
        try:
            excelData = object()
            if (file_name.endswith('.xls')):
                # "1726122597.xls",
                excelData = self.readXls(file_name, 0)
            elif (file_name.endswith('.xlsx')):
                # "t1.xlsx"
                excelData = self.readXlsx(file_name, 0)

            nameIndex = nfileNames.split(",")

            for row in excelData.itertuples():
                nfilePath = nFilePathDir + "/"
                for i in nameIndex:
                    nfilePath += f"{row[int(i)]}{nfileSegment}"
                if len(nfileSegment) > 0:
                    nfilePath = nfilePath[0:len(nfilePath) - len(nfileSegment)]
                self.crateFileDir(nfilePath)
                nMoveFileName = f"{row[int(moveFileName)]}"
                # print(oldFilePathDir + "/" + nMoveFileName)
                # print(nfilePath + "/" + nMoveFileName)
                shutil.copy2(oldFilePathDir + "/" + nMoveFileName, nfilePath + "/" + nMoveFileName)
            self.processResult("处理完成")
        except BaseException as e:
            self.processResult(f"处理错误{e}")

    def initWindow(self):
        # 获取桌面工作区的实例
        desktop = QDesktopWidget()
        screen_width = desktop.screenGeometry().width()
        screen_height = desktop.screenGeometry().height()

        openWidth = int((screen_width - 1000) / 2)
        openHeight = int((screen_height - 500) / 2)

        form_layout = QGridLayout()
        editFileWidth = 500
        editWidth = 300
        self.excelFile = QLineEdit()
        self.excelFile.setFixedWidth(editFileWidth)
        self.execlExcelBtn = QPushButton("请选择文件", self)
        self.execlExcelBtn.clicked.connect(self.showFileDialog)

        self.orginFilePath = QLineEdit()
        self.orginFilePath.setFixedWidth(editFileWidth)
        self.orginFileBtn = QPushButton("请选择文件夹", self)
        self.orginFileBtn.clicked.connect(lambda: self.showFilePathDialog(self.orginFilePath))

        self.newFilePath = QLineEdit()
        self.newFilePath.setFixedWidth(editFileWidth)
        self.newFileBtn = QPushButton("请选择文件夹", self)
        self.newFileBtn.clicked.connect(lambda: self.showFilePathDialog(self.newFilePath))

        self.fileDirName = QLineEdit()
        self.fileDirName.setFixedWidth(editWidth)
        self.fileName = QLineEdit()
        self.fileName.setFixedWidth(editWidth)
        self.fileFormat = QLineEdit()
        self.fileFormat.setFixedWidth(editWidth)
        self.fileHeader = QLineEdit()
        self.fileHeader.setFixedWidth(editWidth)
        self.fileNameSegment = QLineEdit()
        self.fileNameSegment.setFixedWidth(editWidth)

        form_layout.addWidget(QLabel('excel文件'), 0, 0)
        form_layout.addWidget(self.excelFile, 0, 1)
        form_layout.addWidget(self.execlExcelBtn, 0, 2)

        form_layout.addWidget(QLabel('原始文件路径'), 1, 0)
        form_layout.addWidget(self.orginFilePath, 1, 1)
        form_layout.addWidget(self.orginFileBtn, 1, 2)

        form_layout.addWidget(QLabel('新文件路径'), 2, 0)
        form_layout.addWidget(self.newFilePath, 2, 1)
        form_layout.addWidget(self.newFileBtn, 2, 2)

        form_layout.addWidget(QLabel('文件头'), 3, 0)
        form_layout.addWidget(self.fileHeader, 3, 1)
        form_layout.addWidget(QLabel('文件名称分割符号'), 3, 2)
        form_layout.addWidget(self.fileNameSegment, 3, 3)

        form_layout.addWidget(QLabel('文件夹列'), 4, 0)
        form_layout.addWidget(self.fileDirName, 4, 1)
        form_layout.addWidget(QLabel('文件名称列'), 4, 2)
        form_layout.addWidget(self.fileName, 4, 3)

        self.submitBtn = QPushButton("执行程序", self)
        self.submitBtn.clicked.connect(self.processBtn)
        form_layout.addWidget(self.submitBtn, 5, 0)

        self.msgLabel = QLabel("")
        form_layout.addWidget(self.msgLabel, 6, 1)

        self.resultLabel = QLabel("")
        form_layout.addWidget(self.resultLabel, 7, 1)

        self.setLayout(form_layout)

        self.setGeometry(openWidth, openHeight, 0, 0)

    def processBtn(self):
        msg = self.excelFile.text() + "\n"
        msg += self.orginFilePath.text() + "\n"
        msg += self.newFilePath.text() + "\n"
        msg += self.fileDirName.text() + "\n"
        msg += self.fileName.text() + "\n"
        msg += self.fileHeader.text() + "\n"
        msg += self.fileNameSegment.text() + "\n"
        self.msgLabel.setText(msg)
        self.processResult("处理中")
        # print(self.excelFile.text())
        # print(int(self.fileHeader.text()))
        # print(self.fileDirName.text())
        # print(self.fileNameSegment.text())
        # print(self.newFilePath.text())
        # print(self.orginFilePath.text())
        # print(self.fileName.text())
        self.readExcel(self.excelFile.text(), int(self.fileHeader.text()), self.fileDirName.text(),
                       self.fileNameSegment.text(),
                       self.newFilePath.text(), self.orginFilePath.text(), f"{self.fileName.text()}")

    def processResult(self, txt):
        self.resultLabel.setText(txt)

    def showFileDialog(self):
        # options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog
        # getOpenFileName 单个文件
        fileName, _ = QFileDialog.getOpenFileNames(self, "请选择文件", "", "All Files (*);;Text Files (*.txt)")
        if fileName:
            self.excelFile.setText(fileName[0])

    def showFilePathDialog(self, qLineEdit):
        # options = QFileDialog.Options()
        # options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getExistingDirectory(self, "请选择文件", "")
        qLineEdit.setText(fileName)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

